package com.lbt.writing.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;

public class JWTUtils {
    // 签名密钥
    private static final String SECRET = "WF#S@H5x='UGQ<paR!6Je3";
    // token过期时间（毫秒）
    private static final long EXPIRE_TIME = 12 * 60 *60 * 1000L;
    // 添加一年的过期时间常量
    private static final long ONE_YEAR_EXPIRE_TIME = 365 * 24 * 60 * 60 * 1000L;

    /**
     * 生成token
     * @param username 用户名
     * @param remember 是否记住我
     */
    public static String createToken(String username, boolean remember) {
        try {
            // 根据remember参数选择过期时间
            long expireTime = remember ? ONE_YEAR_EXPIRE_TIME : EXPIRE_TIME;
            Date date = new Date(System.currentTimeMillis() + expireTime);
            Algorithm algorithm = Algorithm.HMAC256(SECRET);

            return JWT.create()
                    .withClaim("username", username)
                    .withExpiresAt(date)
                    .sign(algorithm);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 验证token
     */
    public static boolean verify(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            verifier.verify(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 从token中获取用户名
     */
    public static String getUsername(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("username").asString();
        } catch (Exception e) {
            return null;
        }
    }
}